<?php
class admin_core_Auth_Adapter extends Engine_Adapter
{
	/**
	 * @var Zend_Auth
	 */
	protected $_auth;

	/**
	 * @var Zend_Auth_Adapter_DbTable
	 */
	protected $_authAdapter;

	/**
	 * @return Zend_Auth
	 */
	protected function getAuth()
	{
		if (empty($this->_auth)) {
			$this->_auth = Zend_Auth::getInstance();
		}

		return $this->_auth;
	}

	/**
	 * @return Zend_Auth_Adapter_DbTable
	 */
	protected function getAuthAdapter()
	{
		if (empty($this->_authAdapter)) {
			$this->_authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());

			$this->_authAdapter
				->setTableName('users')
			    ->setIdentityColumn('login')
			    ->setCredentialColumn('password')
			    ->setCredentialTreatment('SHA1(CONCAT(?,salt))');
		}

		return $this->_authAdapter;
	}

	/**
	 * @return bool
	 */
	public function isLogged()
	{
		return $this->getAuth()->hasIdentity();
	}

	/**
	 * @return void
	 */
	public function logout()
	{
		$this->getAuth()->clearIdentity();
	}

	/**
	 * @param array $params
	 * @return bool
	 */
	public function authentificate($params)
	{
		$adapter = $this->getAuthAdapter()
			->setIdentity($params['login'])
			->setCredential($params['password']);

		$auth = $this->getAuth();

		if ($auth->authenticate($adapter)->isValid()) {
		    $auth->getStorage()->write($adapter->getResultRowObject());

		    return true;
		}

		return false;
	}

	/**
	 * @return int
	 */
	public function getId()
	{
		$storage = $this->getAuth()->getStorage()->read();

		return $storage->id;
	}
}